<template>
  <div class="box-viewHistory">
    <!-- :default-selected-keys="defaultSelectedKeys" -->
    <div class="tree-content">
      <el-tree
        ref="treeRef"
        :default-expanded-keys="defaultExpandedKeys"
        :current-node-key="defaultCurrentNodeKey"
        :load="loadNode"
        lazy
        node-key="id"
        highlight-current
        :render-after-expand="false"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
      >
        <template #default="{ node }">
          <span class="node-content" :title="node.label">
            {{ node.label }}
          </span>
        </template>
      </el-tree>
    </div>
    <div class="box-controller">
      <div class="box-search">
        <div class="box-search-left">
          <el-form :inline="true" :model="formParam" style="width: 100%">
            <el-row :gutter="20">
              <!-- 指标名称 -->
              <el-col :span="6">
                <el-form-item label="指标名称:">
                  <el-input v-model="formParam.label" placeholder="请输入角色名称" clearable />
                </el-form-item>
              </el-col>

              <!-- 状态选择 -->
              <el-col :span="4">
                <el-form-item label="状态:">
                  <el-select v-model="formParam.status" placeholder="请选择状态" clearable>
                    <el-option
                      v-for="(item, index) of auditStatusList"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <!-- 预警指标 -->
              <el-col :span="4">
                <el-form-item label="预警指标:">
                  <el-select
                    v-model="formParam.isAlertIndicator"
                    placeholder="请选择状态"
                    clearable
                    style="width: 100%"
                  >
                    <el-option label="是" value="1" />
                    <el-option label="否" value="0" />
                  </el-select>
                </el-form-item>
              </el-col>

              <!-- 更新日期 -->
              <el-col :span="6">
                <el-form-item label="更新日期:">
                  <el-date-picker
                    v-model="tempDateRange"
                    type="daterange"
                    range-separator="-"
                    value-format="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item class="form-item-responsive">
                  <el-button type="primary" class="zdy-btn" @click="searchWay">查询</el-button>
                  <el-button class="zdy-btn" @click="resetForm">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="controller-page">
        <div class="card-table">
          <div class="card-total-txt">
            <span>共搜索到{{ total }}条数据</span>
          </div>
          <div class="table-list">
            <el-table ref="multipleTableRef" :data="dataList" row-key="id" style="width: 100%" height="100%" border>
              <el-table-column type="index" width="60" align="center" label="序号" />
              <el-table-column prop="indicator" align="left" label="指标名称" min-width="200" />

              <el-table-column prop="currentValue" align="left" label="指标值" min-width="140" />
              <el-table-column prop="targetValue" align="left" label="目标值" min-width="140" />

              <el-table-column prop="isAlertIndicator" align="left" label="预警指标" width="140">
                <template #default="scope">
                  <span v-if="scope.row.isAlertIndicator == '1'">是</span>
                  <span v-else-if="scope.row.isAlertIndicator == '0'">否</span>
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column prop="updatedAt" align="left" label="更新时间" min-width="180"> </el-table-column>
              <el-table-column fixed="right" align="left" label="操作" width="200">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click="historyHandle(scope.row)"> 历史数据 </el-button>
                  <el-divider direction="vertical" />
                  <el-button link type="primary" size="small" @click="previewHandle(scope.row)"> 驾驶舱展示 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="card-pagination">
            <el-pagination
              :small="true"
              v-model:current-page="formParam.pageNum"
              v-model:page-size="formParam.pageSize"
              layout="total, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <historyDrawerCom
      :isDrawer="showHistoryDrawer"
      :id="showHistoryDrawerId"
      @close="showHistoryDrawer = false"
    ></historyDrawerCom>
  </div>
</template>

<script setup>
import { ref, watchEffect, reactive } from "vue"
import historyDrawerCom from "./components/historyDrawerCom.vue"
import dayjs from "dayjs"
import { nodeLoading, treeWithLevels } from "../../api/datamanage/fillreport"
import { isEmpty } from "lodash-es"
import { auditsHistory } from "../../api/datamanage/viewHistory"

const treeRef = ref(null)
const defaultExpandedKeys = ref([])
const defaultCurrentNodeKey = ref([])

function handleNodeClick(data) {
  formParam.id = data.id
  getList()
}

const auditStatusList = ref([
  { label: "草稿", value: "1", color: "color-bg-yellow" },
  { label: "等待审批", value: "2", color: "color-bg-blue" },
  { label: "审批通过", value: "3", color: "color-bg-green" },
  { label: "审批驳回", value: "0", color: "color-bg-red" },
  { label: "作废", value: "4", color: "color-bg-grey" }
])
const formParam = reactive({
  id: "",
  label: "",
  status: "",
  isAlertIndicator: "",
  startUpdated: "", // 新增开始时间
  endUpdated: "", // 新增结束时间
  pageNum: 1,
  pageSize: 10
})
const dataList = ref([])
const multipleSelection = ref([])
const total = ref(0)
const tempDateRange = ref([]) // 新增临时日期范围存储

// 在搜索方法前添加监听
watchEffect(() => {
  if (tempDateRange.value && tempDateRange.value.length === 2) {
    formParam.startUpdated = tempDateRange.value[0] + " 00:00:00"
    formParam.endUpdated = tempDateRange.value[1] + " 23:59:59"
  } else {
    formParam.startUpdated = ""
    formParam.endUpdated = ""
  }
})

function searchWay() {
  formParam.pageNum = 1
  formParam.pageSize = 10
  getList()
}
const resetForm = () => {
  formParam.label = ""
  formParam.status = ""
  formParam.isAlertIndicator = ""
  tempDateRange.value = [] // 重置临时日期范围
  formParam.startUpdated = ""
  formParam.endUpdated = ""
  searchWay()
}

function handleSizeChange(val) {
  formParam.pageSize = val
  getList()
}
function handleCurrentChange(val) {
  formParam.pageNum = val
  getList()
}

const loadNode = async (node, resolve) => {
  // 根节点首次加载
  if (node.level === 0) {
    const { data } = await treeWithLevels()
    processInitialData(data)

    resolve(data)
    return
  }

  // 后续节点加载
  if (node.level < 4) {
    // 前三级使用预加载数据
    return resolve(node.data.children || [])
  } else {
    // 三级之后动态加载
    const { data } = await nodeLoading(node.data.id)
    if (isEmpty(data)) return resolve([])
    return resolve(data)
  }
}

function processInitialData(data) {
  const keys = []
  const process = (nodes, level) => {
    nodes.forEach((node) => {
      keys.push(node.id)
      node.isLeaf = level === 3 // 第三级标记为非叶子节点
      if (node.children && level < 3) {
        process(node.children, level + 1)
      }
    })
  }

  process(data, 1)
  defaultExpandedKeys.value = keys
  defaultCurrentNodeKey.value = isEmpty(data) ? [] : data[0].id
  formParam.id = data[0].id
  getList()
}

// 获取指标列表
async function getList() {
  const { data } = await auditsHistory(formParam)
  // 模拟数据
  dataList.value = data.records
  total.value = data.total
}

const showHistoryDrawer = ref(false) // 控制历史数据抽屉的显示隐藏

const showHistoryDrawerId = ref("")
// 历史数据
function historyHandle(row) {
  showHistoryDrawerId.value = row.id
  showHistoryDrawer.value = true
}
// 预览
function previewHandle(row) {}
</script>
<style scoped lang="scss">
:deep(.el-tree--highlight-current) {
  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #f5f7fa;
    .node-content {
      color: #0c7cff;
      font-weight: 500;
    }
  }
}
.color-bg-yellow {
  background-color: #faad14;
}
.color-bg-green {
  background-color: #52c41a;
}
.color-bg-blue {
  background-color: #0c7cff;
}
.color-bg-red {
  background-color: #ff4d4f;
}
.color-bg-grey {
  background-color: #999999;
}

.box-viewHistory {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #f0f0f0;
  padding: 20px 20px 0 20px;
  display: flex;
  flex-direction: row;
  box-sizing: border-box;
  .tree-content {
    width: 320px;
    height: 100%;
    padding: 20px 10px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    border-right: 1px solid #e5e6eb;
    overflow: hidden;
    overflow-y: auto;
    box-sizing: border-box;
    .node-content {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      display: block;
    }
  }
  .box-search {
    width: 100%;
    min-height: 40px;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    ::v-deep .box-search-left {
      width: auto;
      height: 100%;
      display: flex;
      flex: 1;
      align-items: center;
      box-sizing: border-box;

      .el-form-item {
        margin-bottom: 0;
      }
      .el-row {
        line-height: 45px;
      }
      .form-item-responsive .el-form-item__content {
        width: 100%;
        display: flex;
        justify-content: end;
      }
      .el-range-editor.el-input__wrapper {
        width: 240px !important;
      }
      .el-form--inline .el-form-item {
        display: inline-flex;
        margin-right: 0;
        vertical-align: middle;
        width: 100%;
      }
    }
    .box-search-right {
      width: auto;
      height: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: flex-start;
      padding-left: 20px;
      padding-top: 2px;
      box-sizing: border-box;
      ::v-deep .zdy-input {
        width: 264px;
        height: 34px;
        line-height: 34px;
        background: #ffffff;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        margin-right: -2px;
        .el-input__wrapper {
          border-radius: 2px 0 0 2px;
        }
      }
      ::v-deep .zdy-btn {
        width: 56px;
        height: 34px;
        line-height: 34px;
        border-radius: 0;
        border-radius: 0px 2px 2px 0px;
      }
    }
  }
  .box-controller {
    width: calc(100% - 320px);
    height: 100%;
    // overflow: hidden;
    display: flex;

    background-color: #fff;
    padding: 15px 15px 10px;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
  }
  .controller-page {
    width: 100%;
    flex: 1;
    overflow: hidden;
  }
}

.card-table {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-sizing: border-box;
  overflow: hidden;
}
.card-total-txt {
  width: 100%;
  height: 20px;
  line-height: 20px;
  font-family:
    Microsoft YaHei,
    Microsoft YaHei;
  font-weight: 400;
  font-size: 14px;
  color: #999999;
  text-align: left;
  font-style: normal;
  text-transform: none;
  margin: 9px 0 5px 0;
}
.btn-group-tool {
  width: 100%;
  height: 40px;
  line-height: 40px;
}
.btn-group-notice {
  width: 100%;
  height: 32px;
  line-height: 32px;
  background: #e6f1ff;
  border-radius: 2px 2px 2px 2px;
  border: 1px solid #0c7cff;
  padding: 0 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin: 5px 0;
  .icon {
    width: 16px;
    height: 16px;
    color: #0c7cff;
    margin-right: 5px;
  }
  .txt {
    font-family:
      Microsoft YaHei,
      Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }
  .num {
    padding: 0 3px;
    font-family: Helvetica, Helvetica;
    font-weight: bold;
    font-size: 16px;
    color: #0c7cff;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }
}

.table-list {
  width: 100%;
  height: auto;
  display: flex;
  flex: 1;
  box-sizing: border-box;
  overflow: hidden;
  ::v-deep .el-table {
    .el-table__header-wrapper {
      th {
        background-color: #f5f9fc !important;
        color: #333333;
      }
    }
    .el-table__body-wrapper {
      td {
        color: #333333;
      }
    }
  }
}

.card-pagination {
  width: 100%;
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  box-sizing: border-box;
}
</style>
